package com.cy.mall.comm.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description 16进制字符串 SHA-256 加密工具
 * @Author tanyilin
 * @Date 2019/3/22 15:35
 */
public class SHA256Utils {

    /**
     * 得到 16进制字符串 SHA-256 加密字符串
     * @param str
     * @return java.lang.String
     */
    public static String getSha256Str(String str) {

        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     *  将 byte 转为16进制字符串
     * @param bytes
     * @return java.lang.String
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        String temp = null;
        for(int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1){
                //1得到一位的进行补0操作
                sb.append("0");
            }
            sb.append(temp);
        }
        return sb.toString();
    }
}
